package com.zy.composeworld.base.adapter

import com.zy.composeworld.base.bean.BaseMenuBean
import androidx.recyclerview.widget.RecyclerView
import com.zy.composeworld.base.adapter.BaseActivityAdapter.BaseViewHolder
import android.view.ViewGroup
import android.view.LayoutInflater
import android.view.View
import com.zy.composeworld.databinding.BaseMenuBodyItemBinding
import com.zy.composeworld.databinding.BaseMenuHeadItemBinding
import com.zy.composeworld.ktx.singleClick

class BaseActivityAdapter(private var mainBeanList: List<BaseMenuBean>) :
    RecyclerView.Adapter<BaseViewHolder>() {

    override fun onCreateViewHolder(viewGroup: ViewGroup, type: Int): BaseViewHolder {
        return if (type == BaseMenuBean.HEAD) {
            BaseHeadViewHolder(BaseMenuHeadItemBinding.inflate(LayoutInflater.from(viewGroup.context)))
        } else {
            BaseBodyViewHolder(BaseMenuBodyItemBinding.inflate(LayoutInflater.from(viewGroup.context)))
        }
    }

    override fun onBindViewHolder(viewHolder: BaseViewHolder, position: Int) {
        viewHolder.bind(mainBeanList[position])
    }

    override fun getItemViewType(position: Int): Int {
        return mainBeanList[position].type
    }

    override fun getItemCount(): Int {
        return mainBeanList.size
    }

    abstract inner class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        abstract fun bind(bean: BaseMenuBean?)
    }

    internal inner class BaseHeadViewHolder(val binding: BaseMenuHeadItemBinding) :
        BaseViewHolder(binding.root) {


        override fun bind(bean: BaseMenuBean?) {
            if (bean != null) {
                binding.baseMenuHeadTitle.text = bean.des
            }
        }
    }

    internal inner class BaseBodyViewHolder(val binding: BaseMenuBodyItemBinding) :
        BaseViewHolder(binding.root) {
        private var bean: BaseMenuBean? = null

        init {
            binding.baseMenuItemTitle.singleClick { v ->
                val tmpBean = bean ?: return@singleClick

                tmpBean.click?.let { click ->
                    click.invoke(v)
                    return@singleClick
                }

                tmpBean.clickWithCode?.let { click ->
                    click.invoke(v, tmpBean.code)
                    return@singleClick
                }
            }
        }

        override fun bind(bean: BaseMenuBean?) {
            this.bean = bean
            bean ?: return
            binding.baseMenuItemTitle.text = bean.des
        }
    }
}